from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from day8.models import *
import re,random,redis,string
from utils.rly import send_message
from captcha.image import ImageCaptcha
# Create your views here.

class Syzm(APIView):
    def get(self,request):
        phone=request.query_params.get("phone")
        if not re.findall(r'^1[3-9]\d{9}$',phone):
            return Response({'code':400,'msg':'手机号格式错误'})
        resp=send_message.delay(phone)
        print(resp)
        return Response({"code":200,'msg':'发送成功'})

# class Zhu(APIView):
#     def post(self,request):
#         phone=request.data.get('phone')
#         yzm=request.data.get('yzm')
#         if not all([phone,yzm]):
#             return Response({'code':400,'msg':'字段不完整'})
#         if not re.findall(r'^1[3-9]\d{9}$',phone):
#             return Response({'code':400,'msg':'手机号格式错误'})
#         r=redis.Redis(host='127.0.0.1',port=6379,db=1)
#         yzm2=r.get(f'sms_code_{phone}')
#         if yzm2:
#             yzm2=yzm2.decode()
#         else:
#             return Response({"code": 400, 'msg': '验证码过期'})
#         if str(yzm2)!=str(yzm):
#             return Response({"code": 400, 'msg': '验证码错误'})
#         User.objects.create(
#             phone=phone,
#         )
#         return Response({'code':200,'msg':'注册成功'})

class Img(APIView):
    def get(self,request,uuid):
        img_code=''.join(random.sample(string.ascii_letters + string.digits,4))
        cap=ImageCaptcha()
        img=cap.generate(img_code)
        r=redis.Redis(host='localhost',port=6379,db=4)
        r.set(uuid,img_code,ex=300)
        r.close()
        return HttpResponse(img,content_type='image/png')
    def post(self,request,uuid):
        c1=request.data.get('imgcode')
        r = redis.Redis(host='localhost', port=6379, db=4)
        c2=r.get(uuid)
        if c2:
            c2=c2.decode()
        else:
            return Response({'code': 400, 'msg': '图片验证码失效'})
        if c1.lower()==c2.lower():
            return Response({'code': 200, 'msg': '图片验证码成功'})
        else:
            return Response({'code': 402, 'msg': '图片验证码不一致'})

from day08.settings import SECRET_KEY
import jwt
def g_jwt(user):
    lst={
        'id': user.id,
        'phone':user.phone
    }
    tolen=jwt.encode(payload=lst,algorithm="HS256",key=SECRET_KEY)
    return tolen

class Deng(APIView):
    def post(self,request):
        phone =request.data.get('phone')
        yzm=request.data.get('yzm')
        if not all([phone,yzm]):
            return Response({'code':400,'msg':'字段不完整'})
        if not re.findall(r"^1[3-9]\d{9}$",phone):
            return Response({'code':401,'msg':'手机号不符合规则'})
        r=redis.Redis(host="127.0.0.1",port=6379)
        c1=r.get(phone)
        r.close()
        if c1:
            c1 =c1.decode()
        else:
            return Response({'code':401,'msg':'验证码已过期'})
        if c1 !=yzm:
            return Response({'code':402,'msg':'验证码错误'})
        try:
            login =User.objects.get(phone=phone)
        except:
            return Response({'code':400,'msg':'手机号不存在'})
        token=g_jwt(login)
        return Response({'code': 200, 'msg': '登录成功',"token":token,"phone":login.phone})

class Fe(APIView):
    def get(self,request):
        data=Sele.objects.all()
        lst=[]
        for i in data:
            lst.append({
                'id':i.id,
                'name':i.name
            })
        return Response({"code":200,'msg':'类别成功','data':lst})

class Xq(APIView):
    def post(self,request):
        id = request.data.get('id')
        print('shiuafbg', id)
        data=Goods.objects.filter(lei_id=id)
        lst=[]
        for i in data:
            lst.append({
                'id':i.id,
                'name':i.name,
                'ping':i.ping,
                'shou':i.shou,
                'zhuan':i.zhuan,
            })
        return Response({"code": 200, 'msg': '详情成功', 'data': lst})
